package com.tucue.controller;

import com.tucue.dao.*;
import com.tucue.model.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tutu on 15/1/17.
 */
public class BaseController {

    public SqlSession sqlSession=null;
    public ModelAndView view = new ModelAndView();

    public void getSqlSession()
    {
        try {
            if (sqlSession == null) {
                String resource = "com/tucue/applicationContext-mybatis.xml";
                InputStream ins = Resources.getResourceAsStream(resource);
                SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(ins);
                sqlSession = sqlMapper.openSession();
            }
        }
        catch (IOException ioe)
        {
            System.out.println(ioe.toString());
            ioe.printStackTrace();
        }
    }

    public void closeSqlSession() {
        sqlSession.close();
        sqlSession=null;
    }

    public void printErros(BindingResult result)
    {
        if(result.hasErrors()) {
            List<FieldError> errors = result.getFieldErrors();
            for(FieldError err : errors) {
                System.out.println("ObjectName:" + err.getObjectName() + "\tFieldName:" + err.getField()
                        + "\tFieldValue:" + err.getRejectedValue() + "\tMessage:" + err.getDefaultMessage());
            }
        }
    }
    //TAO:IDlist字符串形式转换为List<Integer>
    public  List<Integer> getIdList(String idstr,String splitcahr)
    {
        String[] sourceStrArray=idstr.split(splitcahr);
        List<Integer> idlist=new ArrayList<Integer>();
        for(int i=0;i<sourceStrArray.length;i++)
        {
            idlist.add(Integer.parseInt(sourceStrArray[i]));
        }
        return idlist;
    }


    //杨俊生自己用的错误输出
    public String printError(BindingResult result) {
            List<FieldError> errors = result.getFieldErrors();
            for(FieldError err : errors) {
                System.out.println("ObjectName:" + err.getObjectName() + "\tFieldName:" + err.getField()
                        + "\tFieldValue:" + err.getRejectedValue() + "\tMessage:" + err.getDefaultMessage());
            }
        return "Error";
    }

    public Date getCurrentTimeStamp()
    {
        DateFormat df   =   new SimpleDateFormat( "yyyy-MM-dd   HH:mm:ss ");
        String currenttime =df.format(new Date());
        try
        {
            Date date=df.parse(currenttime);
            return date;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    //杨俊生用的转换表单时间类型方法（String to Date）
    public Date getDateTime(HttpServletRequest request,String name){
        DateFormat df  =  new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        try {
            Date date = df.parse(request.getParameter(name));
            return date;
        } catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    //杨俊生用的返回字符串类型的当前时间 对应Loanservice和ServiceProvider两张表
    public String geStringTimeStamp() {
        DateFormat df   =   new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        String currenttime =df.format(new Date());
        return currenttime;
    }

    public String getSuccessPage()
    {
        return "success";
    }

    public String getErrorPage()
    {
        return "error";
    }


    //杨俊生用的插入操作备注记录方法
    public void createLog(HttpServletRequest request,String category,int id){
        Log log=new Log();
        log.setContent(request.getParameter("logContent"));
        log.setSourcetable(category);
        log.setUpdatetime(getCurrentTimeStamp());
        log.setRecordidintable(id);
        LogMapper logmapper=sqlSession.getMapper(LogMapper.class);
        logmapper.insert(log);
        sqlSession.commit();
    }

    //杨俊生用的上传附件和插入数据库记录方法
    public void insertFile(@RequestParam MultipartFile[] files,HttpServletRequest request,String Sourcetable,int id)throws IOException{
        //服务器中的存储路径
        String storePath=request.getSession().getServletContext().getRealPath("/uploadfiles");

        //若目录不存在则创建
        File UploadDir = new File(storePath);
        if (!UploadDir.exists()) UploadDir.mkdir();

        ResourceMapper ResourceMapper=sqlSession.getMapper(ResourceMapper.class);

        for(MultipartFile file:files) {
            if(file.isEmpty())continue;
            //创建文件输出流
            File f=new File(storePath+"/"+file.getOriginalFilename());
            FileOutputStream out=new FileOutputStream(f);
            //复制文件到服务器目录
            FileCopyUtils.copy(file.getInputStream(),out);
            //插入资源关联表记录
            Resource resource =new Resource();
            resource.setSourcetable(Sourcetable);
            resource.setCreatetime(getCurrentTimeStamp());
            resource.setRecordidintable(id);

            resource.setFilename(file.getOriginalFilename());
            resource.setSize((int) file.getSize());
            resource.setPath(storePath);
            ResourceMapper.insert(resource);
            sqlSession.commit();
        }
    }

    //杨俊生用的用户关联到模块
    public void usermodule(User user){
        UserModule userModule=new UserModule();
        userModule.setUserid(user.getUserid());
        userModule.setModuleid(user.getType());

        UserModuleMapper userModuleMapper=sqlSession.getMapper(UserModuleMapper.class);
        userModuleMapper.insert(userModule);
        sqlSession.commit();
    }

    //杨俊生用的创建订单时初始化订单状态记录方法
    public void orderStatus(int orderId,int userId,int category){
        OrderStatus orderStatus=new OrderStatus();
        orderStatus.setOrderid(orderId);
        orderStatus.setUserid(userId);
        orderStatus.setCategory(category);

        OrderStatusMapper orderStatusMapper=sqlSession.getMapper(OrderStatusMapper.class);
        orderStatusMapper.insert(orderStatus);
        sqlSession.commit();
    }

    //杨俊生用的创建服务关联表记录方法
    public void createService(int serviceProviderId,String productId,int category){

        Service service=new Service();
        service.setCategory(category);
        service.setServiceproviderid(serviceProviderId);
        service.setProductid(Integer.parseInt(productId));
        service.setVisible(1);

        ServiceMapper serviceMapper=sqlSession.getMapper(ServiceMapper.class);
        serviceMapper.insert(service);
        sqlSession.commit();
    }


    //杨俊生用的获得session中的用户id
    public User getCurrentUser(HttpSession session){
        User u= (User)session.getAttribute("userInSession");
        return u;
    }


    //杨俊生用的获得session中的用户id
    public int getUserId(HttpSession session){
        User user=(User)session.getAttribute("userInSession");
        return user.getUserid();
    }

    //杨俊生用的创建实施区域关联表记录方法
    public void itemRegion(int itemId,String regionId,int category){

        Item2Region  item2Region=new Item2Region();
        item2Region.setCategory(category);
        item2Region.setItem2regionid(itemId);
        item2Region.setRegionid(Integer.parseInt(regionId));

        Item2RegionMapper item2RegionMapper=sqlSession.getMapper(Item2RegionMapper.class);
        item2RegionMapper.insert(item2Region);
        sqlSession.commit();
    }

    //杨俊生点击新建按钮跳转到新建页面改变表单的action属性 //git真好用啊
    @RequestMapping("/toAddPage")
    public String toAddPage(ModelMap model,@RequestParam String pageUrl) {
        model.addAttribute("addOrUpdate", "add");
        return pageUrl;
    }

    //点击新建按钮跳转新建咨询页面 园区和app的新建咨询室同一张页面
    @RequestMapping(value="/toConsult",method = RequestMethod.GET)
    public String toConsult(ModelMap model,@RequestParam String consultType) {
        model.addAttribute("consultType", consultType);
        model.addAttribute("addOrUpdate", "add");
        return "appNewConsultancy";
    }
}
